const MD5 = require('./md5');
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatTimeminute(date) {
  // var year = date.getFullYear()
  // var month = date.getMonth() + 1
  // var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  // var second = date.getSeconds()

  return  [hour, minute].map(formatNumber).join('小时')
}
function formatDate(date){
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  return [year, month].map(formatNumber).join('-')
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function randomString(len) {
　　len = len || 32;
　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
　　var maxPos = $chars.length;
　　var pwd = '';
　　for (let i = 0; i < len; i++) {
　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
　　}
　　return pwd;
}

function _toQueryPair(key, value) {
  if (typeof value == 'undefined'){
    return key;
  }
  return key + '=' + (value === null ? '' : String(value));
}

function toQueryString(obj) {
  var ret = [];
  for(var key in obj){
  var values = obj[key];
  if(values && values.constructor == Array){//数组
  var queryValues = [];
  for (var i = 0, len = values.length, value; i < len; i++) {
    value = values[i];
    if(values !== '' && values !== undefined && values !== null) {
      queryValues.push(_toQueryPair(key, value));
    }
  }
    ret = ret.concat(queryValues);
  }else{ //字符串
      if(values !== '' && values !== undefined && values !== null) {
        ret.push(_toQueryPair(key, values));
      }
  }
  }
  return ret.sort().join('&');
}

function signToParam(user,param) {
  param.curtime = Date.parse(new Date());
  param.noncestr = randomString(12);
  var searchs = toQueryString(param);
  if(user && typeof user.key === 'undefined') {
    user.key = '';
  }
  var querys = searchs + '&key=' + user.key;
  param.sign = MD5.md5(querys).toUpperCase();
}

function convertObjToUrlQuery(data) {
  var _result = [];
  for (var key in data) {
    var value = data[key];
    if (value.constructor == Array) {
      value.forEach(function(_value) {
        _result.push(key + "=" + _value);
      });
    } else {
      _result.push(key + '=' + value);
    }
  }
  return _result.join('&');
}

module.exports = {
  formatTime: formatTime,
  formatTimeminute:formatTimeminute,
  formatDate:formatDate,
  randomString: randomString,
  toQueryString: toQueryString,
  signToParam:signToParam,
  convertObjToUrlQuery:convertObjToUrlQuery
}
